package org.lionel.clazz;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo1 {
    public static void main(String[] args) {

        PrintXYZ printXYZ = new PrintXYZ();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                printXYZ.printX();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                printXYZ.printY();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                printXYZ.printZ();
            }
        }, "C").start();
    }
}

class PrintXYZ {

    private int num = 0;

    private final Lock lock = new ReentrantLock();

    private final Condition condition = lock.newCondition();

    public void printX() {
        System.out.println("printX:start:"+num);
        lock.lock();
        try {
            while (num != 0) {
                condition.await();
            }
            num++;
            System.out.println("printX:end:"+num);
            System.out.println(Thread.currentThread().getName() + "线程打印 X");
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printY() {
        System.out.println("printY:start:"+num);
        lock.lock();
        try {
            while (num != 1) {
                condition.await();
            }
            num++;
            System.out.println("printY:end:"+num);
            System.out.println(Thread.currentThread().getName() + "线程打印 Y");
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printZ() {
        System.out.println("printZ:start:"+num);
        lock.lock();
        try {
            while (num != 2) {
                condition.await();
            }
            num = 0;
            System.out.println("printZ:end:"+num);
            System.out.println(Thread.currentThread().getName() + "线程打印 Z");
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

